<?php

namespace App\Livewire;

use App\Models\Video;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\Paginator;
use Livewire\Component;
use Livewire\WithPagination;

class VideoPartList extends Component
{
    use WithPagination;

    public int $perPage = 4;

    public int $category = 0;

    public bool $topBig = false;

    public function render()
    {
        $videos = $this->videos();
        $changeBatch = sprintf("%s('%s')", $videos->hasMorePages() ? 'nextPage' : 'resetPage', $this->getPageName());

        return view('livewire.video-part-list', compact('videos', 'changeBatch'));
    }

    public function videos(): Paginator
    {
        return Video::when($this->category, fn (Builder $query, int $category) => $query->whereHas('categories', fn (Builder $query) => $query->where('id', $category)))
            ->latest()
            ->simplePaginate($this->perPage, pageName: $this->getPageName());
    }

    protected function getPageName(): string
    {
        return sprintf('page-%u', $this->category);
    }

    public function placeholder()
    {
        return view('livewire.placeholders.video-part', [
            'topBig' => $this->topBig,
            'perPage' => $this->perPage,
        ]);
    }
}
